<template>
  <div class="clue_allot_page">
    <div class="tab">
      <Tabs type="card" v-model="showTab" :animated="false" @on-click="tabClickFun">
        <TabPane :label="label1" name="clueClient"></TabPane>
        <!-- <TabPane :label="label2" name="cluePrivacy" v-if="cluePrivacyFlag"> -->
        <TabPane :label="label2" name="cluePrivacy"></TabPane>
      </Tabs>
    </div>
    <div>
      <top-count :customerType="customerType" />

      <div class="tips" v-if="showTab == 'clueClient' && customerType == 1">
        <Icon type="ios-alert" size="24" color="#2d8cf0" />
        请选择需分出的客户（注意：如果将客户分配给非“顾问”角色人员，则分配后无法发起认购或签约
      </div>
      <div class="tips" v-if="showTab == 'clueClient'">
        <Icon type="ios-alert" size="24" color="#2d8cf0" />
        请选择需分出的客户（注意：顾问的“私客”将被隐藏，不可分配。
        <Tooltip
          content="“私客” 指由顾问自主获取的线索客户，包括：手动录入客户、通过自主发送的营销工具获取的客户"
          placement="top">
          <span>什么是“私客”？</span>
        </Tooltip>
        ）
      </div>

      <div class="tips" v-if="showTab == 'cluePrivacy'">
        <Icon type="ios-alert" size="24" color="#2d8cf0" />
        请选择需分出的客户（注意：“隐私号客户”只可分配给承接人。
        <Tooltip content="“承接人”指已配置虚拟号的顾问" placement="top">
          <span>什么是“承接人”？</span>
        </Tooltip>
        ）
      </div>
    </div>

    <div class="privaClass flex flex-direction-row flex-horizontal-end">
      <span>已选{{ customerChoosedLength }}组，共{{ page.total }}组客户</span>
      <span type="success" class="btnChenClass" v-if="customerType != 2 && unlocking('0101020200')">
        <Checkbox v-model="privateFlag" @on-change="privateChange" class="checkClass">显示私客</Checkbox>
      </span>
      <Button type="primary" @click="onAllot">分出已选客户</Button>
      <Button type="error" @click="onAllotAll">分出全部客户</Button>
      <Button type="primary" @click="assignClueCustomersRecord">分配记录</Button>

      <!-- <Button class="adjust_header" type="primary" @click="adjustHeader"
        v-if="unlocking('0101010300')">调整表头排序</Button> -->
    </div>

    <!-- <dynamic-header ref="dynamicHeader" @fieldCancel="fieldCancel" @headUpdate="headUpdate"
      :sourcedata="sourcedata" :targetdata="targetdata"></dynamic-header> -->
    <dt-grid
      ref="table"
      :select="select"
      :columns="columns"
      :page="page"
      :onFetch="onFetch"
      :cell-height="80" />

    <allot-modal ref="allot" @detailsDistributeClue="detailsDistributeClue" />
    <preview-image :images="preViewImg" :showIndex="showIndex" ref="preViewImage"></preview-image>
  </div>
</template>

<script>
  import allotColumnOpt from './opt/allotColumn'
  import clueCustomerMgr from '@/biz/customer/clueCustomer.js'
  import customerOptMgr from '@/biz/customer/customerOpt.js'
  // import dynamicHeader from '@/components/dynamicHeader.vue'
  import allotModal from '../assignCustomersRecord/components/allot-modal.vue'
  import receiverMgr from '@/biz/receiver/receiver'
  import topCount from '../components/topCount.vue'

  // // 线索
  // import clueColumnConfig from '../clueCustomer/opt/column'
  // // 到访
  // import visitColumnConfig from '../opt/customerColumn'
  // 公客池
  import publicColumnOpt from '../publicCustomer/opt/column'

  export default {
    components: {
      // dynamicHeader,
      allotModal,
      topCount
    },
    data() {
      return {
        customerType: '1',
        privateFlag: false,
        // 3.7.2

        loading: false,
        columns: [],
        userCustomerId: [],
        customerChoosedLength: 0,
        showTab: 'clueClient',
        oldShowTab: 'clueClient',
        // sourcedata: [],
        // targetdata: [],
        select: {
          change: (e) => {
            this.tableChange(e)
          }
        },
        waitAllotNum: 0,

        retain: '', //是否保留
        authType: '',
        label1: '线索客户',
        label2: '隐私号客户',
        // label1: (h) => {
        //   return h('div', [h('span', '线索客户')])
        // },
        // label2: (h) => {
        //   return h('div', [h('span', '隐私号线索客户')])
        // },
        clueWaitAllotNum: 0,
        cluePrivacyWaitAllotNum: 0,
        page: {
          total: 0,
          current: 1
        },
        queryType: '',
        showIndex: 0,
        preViewImg: [],
        cluePrivacyFlag: false,
        userCustomerIdRoute: [] //代办任务跳转
      }
    },
    created() {
      // this.customerType = this.$route.query.customerType
      this.customerType = 2
      if (this.customerType == 1) {
        this.label1 = '线索客户'
      } else if (this.customerType == 2) {
        this.label1 = '到访客户'
      } else if (this.customerType == 3) {
        this.label1 = '公客池客户'
      }
    },

    async mounted() {
      //代办任务跳转
      this.showTab = this.$route.params.isMaskPhone == 1 ? 'cluePrivacy' : 'clueClient'
      this.oldShowTab = this.showTab
      this.authType = this.unlocking('0101020200') ? 'big' : this.unlocking('0101020700') ? 'little' : ''
      this.userCustomerId = this.$route.params.clueCustomerList ? this.$route.params.clueCustomerList : []
      this.clueDistributionListCount()
      // await this.getReceiver()
      await this.getColumns()
      clueCustomerMgr.getConsultant()
      clueCustomerMgr.getFilterOptions()
      clueCustomerMgr.getChannel()
      clueCustomerMgr.getArea()
      this.$refs.table.init(this)
      this.$refs.table.fetch()
    },
    methods: {
      count() {
        if (this.customerType == '1') {
          let params = {
            buildingId: this.$dt.buildInfo().housesId,
            ...data,
            isMask: this.cluePrivacyFlag && this.showTab == 'cluePrivacy' ? 1 : 0,
            queryType: this.queryType,
            permissionsCode: this.unlocking('0101020200') ? 1 : this.unlocking('0101020700') ? 2 : null,
            userCustomerId: this.userCustomerId
          }
          return clueCustomerMgr.clueCustomerList(params).then((res) => {
            res.records &&
              res.records.forEach((item) => {
                if (item.featurePhoto) {
                  item.featurePhoto = item.featurePhoto.split(',')
                } else {
                  item.featurePhoto = []
                }
              })
            this.page.total = res.total
            res.list = res.records
            console.log(res, this.page.total, '333333')
            return res
          })
        }
      },
      privateChange() {},
      // 3.7
      // getBadge(h, txt, num) {
      //   return h('div', [
      //     [h('span', txt)],
      //     h('Badge', {
      //       props: {
      //         count: num,
      //       },
      //     })
      //   ])
      // },
      tabClickFun(val) {
        if (this.oldShowTab == val) return false
        this.oldShowTab = val
        this.userCustomerId = []
        this.customerChoosedLength = 0
        this.queryType = null
        this.$refs.table.clearFilter()
        this.$refs.table.fetch(true)
      },
      //立即查看
      onCheckAllot() {
        this.userCustomerId = []
        this.customerChoosedLength = 0
        this.queryType = 1 // 1待分配 不穿查询全部
        this.$refs.table.clearFilter()
        this.$refs.table.fetch(true)
      },
      lookImg(val) {
        this.preViewImg = val
        this.$refs.preViewImage.show()
      },
      tableChange(val) {
        this.userCustomerId = []
        if (val && val.length) {
          this.customerChoosedLength = val.length
          val.forEach((item) => {
            if (item.userCustomerId) {
              this.userCustomerId.push(Number(item.userCustomerId))
            }
          })
        } else {
          this.userCustomerId = []
          this.customerChoosedLength = 0
        }
      },
      // fieldCancel() {
      //   this.$refs.dynamicHeader.hide()
      // },
      // adjustHeader() {
      //   this.$refs.dynamicHeader.show()
      // },
      // headUpdate(params) {
      //   params.type = 3
      //   clueCustomerMgr.clueHeadUpdate(params).then((res) => {
      //     this.getColumns()
      //     this.$nextTick(function() {
      //       this.$refs.dynamicHeader.hide()
      //     })
      //   })
      // },
      //获取表头
      getColumns() {
        if (this.customerType == 1) {
          //线索客户
          return customerOptMgr.columns(true, 1).then((res) => {
            console.log(res, '我是线索客户的表头')
            if (res) {
              this.columns = allotColumnOpt.clueAllotColumns(this, res.resArr, 'chooseBox')
            }
          })
        } else if (this.customerType == 2) {
          return customerOptMgr.columns().then((res) => {
            console.log(res, '我是到访客户表头')
            if (res) {
              this.columns = allotColumnOpt.clueAllotColumns(this, res.resArr, 'chooseBox')
            }
          })
        } else if (this.customerType == 3) {
          this.columns = publicColumnOpt.options(this)
          console.log(this.columns, '公客池表头')
        }
      },

      onFetch(data) {
        // 线索客户
        if (this.customerType == 1) {
          let params = {
            buildingId: this.$dt.buildInfo().housesId,
            ...data,
            isMask: this.cluePrivacyFlag && this.showTab == 'cluePrivacy' ? 1 : 0,
            queryType: this.queryType,
            permissionsCode: this.unlocking('0101020200') ? 1 : this.unlocking('0101020700') ? 2 : null,
            userCustomerId: this.userCustomerId
          }
          return clueCustomerMgr.clueCustomerList(params).then((res) => {
            res.records &&
              res.records.forEach((item) => {
                if (item.featurePhoto) {
                  item.featurePhoto = item.featurePhoto.split(',')
                } else {
                  item.featurePhoto = []
                }
              })
            this.page.total = res.total
            res.list = res.records
            console.log(res, this.page.total, '333333')
            return res
          })
          // 到访客户
        } else if (this.customerType == 2) {
          let params = {
            buildingId: this.$dt.buildInfo().housesId,
            ...data,
            isMask: this.cluePrivacyFlag && this.showTab == 'cluePrivacy' ? 1 : 0,
            queryType: this.queryType,
            permissionsCode: this.unlocking('0101020200') ? 1 : this.unlocking('0101020700') ? 2 : null,
            userCustomerId: this.userCustomerId
          }
          return clueCustomerMgr.clueCustomerList(params).then((res) => {
            res.records &&
              res.records.forEach((item) => {
                if (item.featurePhoto) {
                  item.featurePhoto = item.featurePhoto.split(',')
                } else {
                  item.featurePhoto = []
                }
              })
            this.page.total = res.total
            res.list = res.records
            console.log(res, this.page.total, '333333')
            return res
          })
        } else {
        }
      },
      assignClueCustomersRecord() {
        this.$router.push({
          path: '/allCustomersManagement/assignCustomersRecord'
        })
      },

      // 分配线索
      onAllotAll() {
        this.$Modal.confirm({
          title: '分配客户确认',
          content: `您将分出列表中所有到访客户，共${this.page.total}组。请确认是否继续该操作？`,
          closable: true,
          onOk: () => {
            let flag = this.showTab == 'cluePrivacy' ? true : false
            this.$refs.allot.show(this.userCustomerId, flag, 'all')
          },
          onCancel: () => {}
        })
      },
      onAllot() {
        if (this.userCustomerId.length < 1) {
          this.$Message.error('请先选择需要分配的线索')
        } else {
          let flag = this.showTab == 'cluePrivacy' ? true : false
          this.$refs.allot.show(this.userCustomerId, flag)
        }
      },
      //  onAllot() {
      //   if (this.userCustomerId.length < 1) {
      //     this.$Message.error('请先选择需要分配的线索')
      //     return
      //   }
      //   if (this.authType == 'big') {
      //     this.assignConfirmFlag = true;
      //   } else {
      //     let flag = this.showTab == 'cluePrivacy' ? true : false
      //     this.$refs.allot.show(this.userCustomerId, '1', '', '', flag)
      //   }
      // },
      // 确认分配
      // assignConfirmOk() {
      //   if (this.retain == '') {
      //     this.$Message.warning('请选择选项')
      //   } else {
      //     let flag = this.showTab == 'cluePrivacy' ? true : false
      //     this.$refs.allot.show(this.userCustomerId, this.retain, '', '', flag)
      //   }
      // },

      detailsDistributeClue() {
        this.detailsFlag = false
        this.$refs.table.fetch()
      },
      //获取统计数据要区分
      clueDistributionListCount() {
        let params = {
          buildingId: this.$dt.buildInfo().housesId
        }
        clueCustomerMgr.clueDistributionListCount(params).then((res) => {
          console.log(res, 'resresres')
          this.clueWaitAllotNum = res.notMarkPhoneCustomer
          this.cluePrivacyWaitAllotNum = res.markPhoneCustomer
          // this.label1 = (h) => {
          //   return this.getBadge(h, '线索客户', res.notMarkPhoneCustomer)
          // }
          // this.label2 = (h) => {
          //   return this.getBadge(h, '隐私号线索客户', res.markPhoneCustomer)
          // }
        })
      },
      //查询当前案场是否有隐私号承接人配置
      getReceiver() {
        receiverMgr.getReceiverInfoByBId({ buildingId: this.$dt.buildInfo().housesId }).then((res) => {
          if (res) this.cluePrivacyFlag = true
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .clue_allot_page {
    padding: 20px;

    .tab {
      position: relative;
    }
  }

  .footer {
    text-align: center;
    margin-top: 20px;
    border-top: 1px #eee solid;
    padding-top: 20px;

    button {
      width: 80px;
      margin: 0 10px;
    }
  }

  .tips {
    background: rgba(254, 252, 236, 1);
    display: block;
    width: 700px;
    padding: 5px;

    .ivu-icon-ios-alert:before {
      vertical-align: -2px;
    }

    span {
      cursor: pointer;
      color: #2d8cf0;
      margin-right: 20px;
    }
  }

  .privaClass {
    margin-top: 10px;

    > * {
      margin-left: 10px;
    }

    > span {
      line-height: 30px;
    }

    .btnChenClass {
      width: 120px;
      display: inline-block;
      border: 1px #19be6b solid;
      line-height: 30px;
      text-align: center;
      border-radius: 5px;
      color: #19be6b;
    }

    .checkClass {
      line-height: 30px;
      width: 100%;
    }
  }
</style>
